#!/bin/bash
#Switch the yum source
mkdir -p /etc/yum.repos.d/repo_bak/
mv /etc/yum.repos.d/*.repo /etc/yum.repos.d/repo_bak/
curl -o /etc/yum.repos.d/EulerOS-base.repo http://mirrors.myhuaweicloud.com/repo/EulerOS_2_5_base.repo
yum makecache

#Get localhost ip
local_ipaddr=$(curl http://169.254.169.254/latest/meta-data/local-ipv4)

#Install keepalived/lvs
yum install -y keepalived ipvsadm ipvs-fnat ipvs-fnat-tools

#Switch ipvs-fnat
ipvs-switch fnat

#Download script
wget -P /etc/keepalived/ https://documentation-samples.obs.cn-north-4.myhuaweicloud.com/solution-as-code-publicbucket/solution-as-code-moudle/build-high-availability-four-layer-load-balancing/userdata/notify.sh
chmod +x /etc/keepalived/notify.sh

#Conifgure keepalived
mkdir /etc/lvs
mv /etc/keepalived/keepalived.conf /etc/lvs/keepalived.conf

#Write keepalived.conf
cat>/etc/keepalived/keepalived.conf<<EOF
! Configuration File for keepalived

global_defs {
    router_id master_node
}

local_address_group laddr_gl {
    $local_ipaddr
}

vrrp_instance VI_1 {
    state MASTER
    interface eth0
    virtual_router_id 51
    priority 100
    advert_int 1
    authentication {
        auth_type PASS
        auth_pass 123456
    }
    virtual_ipaddress {
        $1
    }
	notify_master "/etc/keepalived/notify.sh master"
	notify_backup "/etc/keepalived/notify.sh backup"
}

#VIP port
virtual_server $1 80 { 
    delay_loop 6
    lb_algo rr
    lb_kind FNAT
    protocol TCP
    laddr_group_name laddr_gl
    #real server
}
EOF
string=$2
RIPList=(${string//,/ })
for rip in ${RIPList[@]}
do
sed -i "36 i \    real_server $rip 80 {" /etc/keepalived/keepalived.conf
sed -i "37 i \        weight 1" /etc/keepalived/keepalived.conf
sed -i "38 i \        TCP_CHECK {" /etc/keepalived/keepalived.conf
sed -i "39 i \            connect_timeout 15" /etc/keepalived/keepalived.conf
sed -i "40 i \            connect_port 80" /etc/keepalived/keepalived.conf
sed -i "41 i \            nb_get_retry 5" /etc/keepalived/keepalived.conf
sed -i "42 i \            delay_before_retry 3" /etc/keepalived/keepalived.conf
sed -i "43 i \        }" /etc/keepalived/keepalived.conf
sed -i "44 i \    }" /etc/keepalived/keepalived.conf
done

#Modify kernel parameters
ipvsadm -Ln
sed -i "s/net.ipv4.ip_forward=0/net.ipv4.ip_forward=1/" /etc/sysctl.conf
sysctl -p

#Start keepalived service
systemctl start keepalived
systemctl enable keepalived